﻿using Microsoft.CSharp.RuntimeBinder;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Asion.Dapper
{
    /// <summary>
    /// 属性解析器
    /// </summary>
    public static partial class SqlMapperExtensions
    {
        public interface ITableNameResolver
        {
            string ResolveTableName(Type type);
        }

        public interface IColumnNameResolver
        {
            string ResolveColumnName(PropertyInfo propertyInfo);
        }

        public class SimpleTableNameResolver : ITableNameResolver
        {
            public virtual string ResolveTableName(Type type)
            {
                var name = type.Name;

                var tableattr = type.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(TableAttribute).Name) as dynamic;
                if (tableattr != null)
                {
                    name = tableattr.Name;
                    try
                    {
                        /*if (!String.IsNullOrEmpty(tableattr.Schema))
                        {
                            string schemaName = tableattr.Schema;
                            tableName = String.Format("{0}.{1}", schemaName, tableName);
                        }*/
                    }
                    catch (RuntimeBinderException)
                    {
                        //Schema doesn't exist on this attribute.
                    }
                }

                return name;
            }
        }

        public class SimpleColumnNameResolver : IColumnNameResolver
        {
            public virtual string ResolveColumnName(PropertyInfo propertyInfo)
            {
                var columnName = propertyInfo.Name;

                var columnattr = propertyInfo.GetCustomAttributes(true).SingleOrDefault(attr => attr.GetType().Name == typeof(ColumnAttribute).Name) as dynamic;
                if (columnattr != null)
                {
                    columnName = columnattr.Name;
                    if (Debugger.IsAttached)
                        Trace.WriteLine(String.Format("Column name for type overridden from {0} to {1}", propertyInfo.Name, columnName));
                }
                return columnName;
            }
        }

    }
}
